//引入封装好的接口
import { userList, getCount } from "../../../request/api";
const state = {
  userlist: [],
  size: 2, //每页显示的条数
  page: 1, //页码
  count: 0, //总条数
};
const getters = {
  getUser(state) {
    return state.userlist;
  },
  //封装总条数方法
  getCount(state) {
    return state.count;
  },
};

const mutations = {
  REQ_LIST(state, payload) {
    state.userlist = payload;
  },
  REQ_COUNT(state, payload) {
    state.count = payload;
  },
  //封装一个修改page的方法
  CHANGE_PAGE(state, payload) {
    state.page = payload;
  },
};

const actions = {
  //列表行动
  getUserAction(context) {
    console.log(context, "行动对象");
    userList({
      size: context.state.size,
      page: context.state.page,
    }).then((res) => {
      if (res.code == 200) {
        let list = res.list ? res.list : [];
        if (context.state.page != 1 && list.length == 0) {
          console.log("重复进入");
          context.dispatch("changePageAction", context.state.page - 1);
        }
        //提交mutations
        context.commit("REQ_LIST", res.list?res.list:[]);
      }
    });
  },
  //获取总条数行动
  getCountAction({ commit }) {
    getCount().then((res) => {
      console.log(res, "管理员的总条数");
      if (res.code == 200) {
        commit("REQ_COUNT", res.list[0].total);
      }
    });
  },
  //封装一个修改页码的行动
  changePageAction(context, payload) {
    // console.log(payload,'payloadpayload');
    //修改page
    context.commit("CHANGE_PAGE", payload);
    //重新调用列表接口
    // console.log(context,'context');
    context.dispatch("getUserAction");
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
  namespaced: true,
};
